import { authAPI, handleApiError, AxiosManager, checkAuthStatus } from '../utils/axiosInstance';
import type { ApiResponse } from '../utils/axiosInstance';

/**
 * 带认证的API请求服务
 */
export class AuthenticatedRequest {
  /**
   * 带认证的GET请求
   */
  public static async get<T = any>(
    url: string,
    params?: Record<string, any>
  ): Promise<ApiResponse<T>> {
    try {
      // 检查是否已登录
      console.log(`[AuthenticatedRequest] 准备发送GET请求到: ${url}`);
      console.log(`[AuthenticatedRequest] 请求参数:`, params);
      checkAuthStatus(); // 添加认证状态检查
      
      if (!AxiosManager.isAuthenticated()) {
        throw new Error('未授权，请先登录');
      }
      
      // 确保authAPI实例已初始化并正确配置
      const token = AxiosManager.getAuthToken();
      if (token && !authAPI.defaults.headers.common['Authorization']) {
        // 手动设置默认头部，作为拦截器的补充保障
        authAPI.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        console.log(`[AuthenticatedRequest] 手动设置Authorization头部: Bearer ${token}`);
      }
      
      // 改进：直接在URL中拼接参数，避免axios的params序列化问题
      let fullUrl = url;
      if (params) {
        const queryParams = new URLSearchParams();
        Object.entries(params).forEach(([key, value]) => {
          queryParams.append(key, String(value));
        });
        const queryString = queryParams.toString();
        if (queryString) {
          fullUrl = `${url}?${queryString}`;
        }
      }
      
      // 使用改进后的URL，不传递params参数
      const response = await authAPI.get<ApiResponse<T>>(fullUrl);
      console.log(`[AuthenticatedRequest] GET请求成功: ${fullUrl}`, response.data);
      return response.data;
    } catch (error) {
      console.error(`[AuthenticatedRequest] GET请求失败: ${url}`, error);
      
      // 特殊处理网络错误
      if (error instanceof Error && error.message.includes('Network Error')) {
        console.error(`[AuthenticatedRequest] 网络连接错误，请检查后端服务是否运行`);
      }
      
      // 增强：记录更详细的错误信息
      if (error instanceof Error) {
        console.error(`[AuthenticatedRequest] 错误详情:`, error.message);
        console.error(`[AuthenticatedRequest] 错误堆栈:`, error.stack);
      }
      
      return handleApiError(error);
    }
  }
  
  /**
   * 带认证的POST请求
   */
  public static async post<T = any>(
    url: string,
    data?: any
  ): Promise<ApiResponse<T>> {
    try {
      // 检查是否已登录
      console.log(`[AuthenticatedRequest] 准备发送POST请求到: ${url}`);
      checkAuthStatus(); // 添加认证状态检查
      
      if (!AxiosManager.isAuthenticated()) {
        throw new Error('未授权，请先登录');
      }
      
      // 确保authAPI实例已初始化并正确配置
      const token = AxiosManager.getAuthToken();
      if (token && !authAPI.defaults.headers.common['Authorization']) {
        // 手动设置默认头部，作为拦截器的补充保障
        authAPI.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        console.log(`[AuthenticatedRequest] 手动设置Authorization头部: Bearer ${token}`);
      }
      
      // 关键修复：处理字符串数据的情况
      let requestData = data;
      const config: any = {};
      
      // 如果数据是字符串，明确设置Content-Type为text/plain
      if (typeof data === 'string') {
        config.headers = {
          'Content-Type': 'text/plain'
        };
      }
      
      // 使用配置发送请求
      const response = await authAPI.post<ApiResponse<T>>(url, requestData, config);
      console.log(`[AuthenticatedRequest] POST请求成功: ${url}`, response.data);
      return response.data;
    } catch (error) {
      console.error(`[AuthenticatedRequest] POST请求失败: ${url}`, error);
      if (error instanceof Error && error.message.includes('Network Error')) {
        console.error(`[AuthenticatedRequest] 网络连接错误，请检查后端服务是否运行`);
      }
      
      return handleApiError(error);
    }
  }

  /**
   * 带认证的PUT请求
   */
  public static async put<T = any>(
    url: string,
    data?: any
  ): Promise<ApiResponse<T>> {
    try {
      // 检查是否已登录
      console.log(`[AuthenticatedRequest] 准备发送PUT请求到: ${url}`);
      checkAuthStatus(); // 添加认证状态检查
      
      if (!AxiosManager.isAuthenticated()) {
        throw new Error('未授权，请先登录');
      }
      
      // 确保authAPI实例已初始化并正确配置
      const token = AxiosManager.getAuthToken();
      if (token && !authAPI.defaults.headers.common['Authorization']) {
        // 手动设置默认头部，作为拦截器的补充保障
        authAPI.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        console.log(`[AuthenticatedRequest] 手动设置Authorization头部: Bearer ${token}`);
      }
      
      const response = await authAPI.put<ApiResponse<T>>(url, data);
      console.log(`[AuthenticatedRequest] PUT请求成功: ${url}`, response.data);
      return response.data;
    } catch (error) {
      console.error(`[AuthenticatedRequest] PUT请求失败: ${url}`, error);
      
      // 特殊处理网络错误
      if (error instanceof Error && error.message.includes('Network Error')) {
        console.error(`[AuthenticatedRequest] 网络连接错误，请检查后端服务是否运行`);
      }
      
      return handleApiError(error);
    }
  }

  /**
   * 带认证的DELETE请求
   */
  public static async delete<T = any>(
    url: string,
    params?: Record<string, any>
  ): Promise<ApiResponse<T>> {
    try {
      // 检查是否已登录
      console.log(`[AuthenticatedRequest] 准备发送DELETE请求到: ${url}`);
      checkAuthStatus(); // 添加认证状态检查
      
      if (!AxiosManager.isAuthenticated()) {
        throw new Error('未授权，请先登录');
      }
      
      // 确保authAPI实例已初始化并正确配置
      const token = AxiosManager.getAuthToken();
      if (token && !authAPI.defaults.headers.common['Authorization']) {
        // 手动设置默认头部，作为拦截器的补充保障
        authAPI.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        console.log(`[AuthenticatedRequest] 手动设置Authorization头部: Bearer ${token}`);
      }
      
      const response = await authAPI.delete<ApiResponse<T>>(url, { params });
      console.log(`[AuthenticatedRequest] DELETE请求成功: ${url}`, response.data);
      return response.data;
    } catch (error) {
      console.error(`[AuthenticatedRequest] DELETE请求失败: ${url}`, error);
      
      // 特殊处理网络错误
      if (error instanceof Error && error.message.includes('Network Error')) {
        console.error(`[AuthenticatedRequest] 网络连接错误，请检查后端服务是否运行`);
      }
      
      return handleApiError(error);
    }
  }
}